package com.chii.auth.controller;

import com.chii.auth.client.UserClient;
import com.chii.auth.po.ResponeInfo;
import com.chii.auth.po.ResultCode;
import com.chii.auth.po.Role;
import com.chii.auth.po.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * UserController
 * 用户认证模块
 *
 * @author Yanzheng https://github.com/micyo202
 * @date 2019/04/08
 * Copyright 2019 Yanzheng. All rights reserved.
 */
@Api("用户认证")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ConsumerTokenServices consumerTokenServices;
    @Autowired
    private UserClient userClient;

    @ApiOperation(value = "获取用户凭证信息", response = ResponeInfo.class)
    @GetMapping(value = "/principal")
    public ResponeInfo principal(Principal principal) {
        //获取用户凭证信息
        ResponeInfo responeInfo = new ResponeInfo();
        responeInfo.setData(principal);
        return responeInfo;
    }

    @ApiOperation(value = "移除用户凭证信息", response = ResponeInfo.class)
    @DeleteMapping(value = "/revoke")
    public ResponeInfo revoke(String access_token) {

        if (consumerTokenServices.revokeToken(access_token)) {
            return new ResponeInfo();
        } else {
            return new ResponeInfo(ResultCode.COMMON_FAIL);
        }
    }

    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ResponeInfo register(@RequestParam("username") String username, @RequestParam("password") String password) throws Exception {
        //获取用户凭证信息
        ResponeInfo responeInfo = userClient.insertNewUser(username, password);
        return responeInfo;
    }

    @ApiOperation(value = "获取用户权限信息")
    @RequestMapping(value = "role", method = RequestMethod.GET)
    public ResponeInfo role(@RequestParam("username") String username) {
        ResponeInfo responeInfo = new ResponeInfo();
        ResponeInfo<User> userResponeInfo = userClient.getUserByUsernameFromUser(username);
        ResponeInfo<List<Role>> listResponeInfo =   userClient.getRoleByUserIdFromUser(userResponeInfo.getData().getId());
        responeInfo.setData(listResponeInfo.getData());
        return responeInfo;
    }
}
